package com.collins.thread.practices.restaurant;

public class Consumer implements Runnable {

    @Override
    public void run() {
        while (true) {
            synchronized (Desk.lock) {
                if (Desk.count == 0) {
                    break;
                } else {
                    // producer waiting, consumer needs to consume
                    if (Desk.flag == 1) {
                        Desk.count--;
                        System.out.println(Thread.currentThread().getName() +
                                " consumes 1 product, current stock is: " + Desk.count);
                        if (Desk.random.nextInt(10) < 5) {
                            Desk.flag = 0;
                        }
                        Desk.lock.notifyAll();
                        try {
                            Thread.sleep(100);
                            // Thread.yield()
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    } else {
                        try {
                            Desk.lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        }
    }
}
